const crypto = require("crypto");

/**
 * 解密小程序加密数据
 */
function decryptWXData(sessionKey, encryptedData, iv) {
    // base64 decode
    const sessionKeyBuf = Buffer.from(sessionKey, 'base64');
    const encryptedDataBuf = Buffer.from(encryptedData, 'base64');
    const ivBuf = Buffer.from(iv, 'base64');

    try {
        const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKeyBuf, ivBuf);
        decipher.setAutoPadding(true);
        let decoded = decipher.update(encryptedDataBuf, 'binary', 'utf8');
        decoded += decipher.final('utf8');
        return JSON.parse(decoded);
    } catch (err) {
        console.error('[wx] 解密失败:', err);
        return null;
    }
}

module.exports = { decryptWXData };
